#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/09/28 08:57
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：
import tools
import sqlite3
import os
import pyodbc
from database_base import Base


class Sql_Client(Base):
    """docstring for Sql_Clinen"""

    def __init__(self, database_path = './config.db', database_type = None, password = None):
        super(Sql_Client, self).__init__()
        self.database_path = database_path
        self._type = database_type
        self.password = password
        self.connect = self.get_connect()

    def get_connect(self):
        file = self.get_database_path()
        if file:
            if self._type.lower() == "sqlite":
                return sqlite3.connect(file, check_same_thread = False)
            elif self._type.lower() == "access":
                ext = os.path.splitext(file)[1][1:].lower()
                driver_list = pyodbc.drivers()
                # odbc驱动
                odbc_driver = [x for x in driver_list[::-1] if ext in x]
                if not odbc_driver:
                    rec = tools.Set_Message("没有accdb驱动，请安装ACCESS2010或以上驱动程序,确认退出，取消继续")
                    if rec == 1:
                        os._exit(0)
                driver_str = "DRIVER={{{}}};DBQ={};Pwd={};ExtendedAnsiSQL=1;".format(odbc_driver[0], file,
                                                                                     self.password or "")
                connect = pyodbc.connect(driver_str, timeout = 1, autocommit = True)
                return connect

    # 加载本地配置
    def get_database_path(self):
        if not os.path.exists(self.database_path):
            tools.setMessage("程序文件夹未找到:文件数据库,请检测配置文件是否存在?", "加载配置")
            os._exit(0)
        else:
            return self.database_path


if __name__ == '__main__':
    db = r"D:\CODE\PYTHON\data_transfer_service\config.db"
    app = Sql_Client(db, 'sqlite')
    print(dir(app))
    print(app.loadSql("select CURRENT_TIMESTAMP", 1))